Thumb

What is Dictionary?

1/11/2020 6:21:23 AM

A dictionary is a collection of keys, value pairs. When we create a dictionary, we need to specify the type for key and value. Dictionary keys in the dictionary must be unique. In the dictionary have some predefined method and key. We can use our needs. When we print the key then we can use the keys key word on the dictionary. Also, we use the values key word for get the value. Given bellow the code and explain the code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using testForClass1;

namespace testFor
{
    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
    public class Program 
    {
        static void Main(string[] args)
        {

            Customer customerOne = new Customer() {Id=1,Name="Farhan",Email="farhan@gmail.com" };
            Customer customerTwo = new Customer() { Id = 3, Name = "Reza", Email = "reza@gmail.com" };
            Customer customerThree = new Customer() { Id = 2, Name = "Sakib", Email = "sakib@gmail.com" };
            Dictionary<int, Customer> customerDictionary = new Dictionary<int, Customer>();
            customerDictionary.Add(customerOne.Id, customerOne);
            customerDictionary.Add(customerTwo.Id, customerTwo);
            customerDictionary.Add(customerThree.Id, customerThree);
            foreach (KeyValuePair<int,Customer> cust in customerDictionary)
            {
                Console.WriteLine("Customer Key: "+cust.Key);
                Console.WriteLine("Id: "+cust.Value.Id+", Name: "+cust.Value.Name+", Email: "+cust.Value.Email);
            }
            Console.Read();
        }
    }
}

In the customer class first, we create three object and initialize the value. Then we create a Dictionary which is key value pair. Now we assign the value then we print the value by using foreach loop. In this loop we use KeyValuePair Type because we use dictionary. Also, we can var key word as well. Then we print the dictionary value by the Console.WriteLine method.